import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'ngx-form-array',
  templateUrl: './form-array.component.html',
  styles: [],
})
export class FormArrayComponent implements OnChanges {
  @Input('fa') fa!: FormArray;
  array: any[] = [];

  constructor(
      private fb: FormBuilder,
  ) {
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['fa']) {
      this.fa = changes['fa'].currentValue;
      this.initData();
    }
  }

  initData() {
    let newFormGroups = [];
    for (let c of this.fa.controls) {
      let newFormGroup = new FormGroup({});
      for (let key of Object.keys((c as any).controls)) {
        let control = (c as any).controls[key];
        newFormGroup.addControl(key, control);
      }
      newFormGroups.push(newFormGroup);
    }
    this.array = newFormGroups || [];
  }

  addObject() {
    let newGroup = this.fb.group({});
    this.fa.controls.push(newGroup);
    this.array.push(newGroup);
  }

  removeObject(idx: number) {
    this.array.splice(idx, 1);
  }
}
